/*
** parse_action.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Tue Jul  5 10:15:28 2011 michael guidet
** Last update Fri Jul  8 08:34:41 2011 michael guidet
*/

#include "server.h"

extern t_action	ia_action[];

void	parse_type(char *cmd, t_fd *fd, t_env *env, int i)
{
  if (!strcmp(cmd, "GRAPHIC"))
    {
      join_graph(fd, env);
      return ;
    }
  for (i = 0; env->teams[i].name; i++)
    {
      if (!strcmp(env->teams[i].name, cmd))
	{
	  player_join_team(fd, &env->teams[i], env);
	  return ;
      }
    }
  if (fd->type == AI || fd->type == UNKNOW)
    add_string_to_list(&fd->send_list, "ko\n");
  else if (fd->type == GRAPH)
    add_string_to_list(&fd->send_list, "suc\n");
}

void	parse_commande(char *cmd, t_fd *fd, t_env *env)
{
  int	i;
  int	j;

  for (i = 0; ia_action[i].cmd != NULL; i++)
    if (!strncmp(cmd, ia_action[i].cmd, strlen(ia_action[i].cmd)))
      {
	for (j = 0; j < 10 && fd->action_list[j] != NULL; j++);
	if (j < 10)
	  fd->action_list[j] = x_null(NULL, strdup(cmd), "strdup");
	return ;
      }
  parse_type(cmd, fd, env, i);
}

void			parse_action(t_fd *cs, t_env *e, char *tmp)
{
  int	i;
  char	**tab;

  x_null(NULL, strcat(tmp, cs->buf_read), "strcat");
  tab = str_to_wordtab(tmp, '\n');
  for (i = 0; tab[i]; i++)
    {
      if (tab[i][strlen(tab[i]) - 1] == '\r')
	tab[i][strlen(tab[i]) - 1] = '\0';
      if (!tab[i + 1])
	if (tmp[strlen(tmp) - 1] != '\n')
	  {
	    add_string_to_list(&cs->receive_list, tab[i]);
	    break ;
	  }
      parse_commande(tab[i], cs, e);
    }
  free(tab[0]);
  free(tab);
  free(tmp);
}
